package com.jpxx.netty.heartBeat;

import java.util.HashMap;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHeartBeatHandler extends ChannelHandlerAdapter{  
    
	private static HashMap<String,String> AUTH_IP_MAP = new HashMap<String, String>();
	
	static{
		AUTH_IP_MAP.put("192.168.2.237","1234");//
	}
	private static final String SUCCESS_KEY = "auth_success_key";
	
	public boolean auth(ChannelHandlerContext ctx, Object msg){
		String[] ret =((String)msg).split(",");
		String auth = AUTH_IP_MAP.get(ret[0]);//1234
		if(auth!=null && auth.equals(ret[1])){
			ctx.writeAndFlush(SUCCESS_KEY);
			return true;
		}else{
			ctx.writeAndFlush("auth failure").addListener(ChannelFutureListener.CLOSE);//服务器断开和客户端的连接
			return false;
		}
	}
	
    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    	 if(msg instanceof String){
    		 auth(ctx,msg);//第一次认证  返回SUCCESS_KEY
    	 }else if(msg instanceof RequestInfo){//以后的都是 返回的RequestInfo
    		 RequestInfo info = (RequestInfo)msg;
    		 System.out.println("-------------------------------------");
    		 System.out.println("当前主机的IP为："+info.getIp());
    		 
    		 System.out.println("当前主机的cpu情况：");
    		 HashMap<String, Object> cpuMap =  info.getCpuPercMap();
    		 System.out.println("总使用率："+cpuMap.get("combined"));
    		 System.out.println("用户使用率："+cpuMap.get("user"));
    		 System.out.println("系统使用率："+cpuMap.get("sys"));
    		 System.out.println("等待率："+cpuMap.get("wait"));
    		 System.out.println("空闲率："+cpuMap.get("idle"));
    		 
    		 System.out.println("当前主机的memory情况：");
    		 HashMap<String, Object> memoryMap =  info.getMemoryMap();
    		 System.out.println("内存总量："+memoryMap.get("total"));
    		 System.out.println("当前内存使用量："+memoryMap.get("used"));
    		 System.out.println("当前内存剩余量："+memoryMap.get("free"));
    		 System.out.println("-------------------------------------");
    		 ctx.writeAndFlush("info接受成功");
    	 }else{
    		 ctx.writeAndFlush("connect failure!!!连接失败!!!").addListener(ChannelFutureListener.CLOSE);//服务器断开和客户端的连接
    	 }
    }  
      
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
        cause.printStackTrace();  
        ctx.close();  
    }  
  
}  
